/*
 * 🕒 增强时间显示和管理模块
 *
 * 功能特性：
 * ✅ 高精度时间同步 (NTP)
 * ✅ 多种OLED显示模式
 * ✅ 智能整点提醒系统
 * ✅ 个性化时间播报
 * ✅ 学习时间统计
 * ✅ 疲劳检测提醒
 *
 * 适配硬件：EBP3901 + 0.96寸OLED (128x64)
 * 作者：AIOT智能学习桌项目组
 */

#ifndef TIME_DISPLAY_ENHANCED_H
#define TIME_DISPLAY_ENHANCED_H

#include <Arduino.h>
#include <WiFi.h>
#include <time.h>
#include <Adafruit_SSD1306.h>

// ========== 时间配置常量 ==========
const char *NTP_SERVER1 = "pool.ntp.org";
const char *NTP_SERVER2 = "time.nist.gov";
const char *NTP_SERVER3 = "cn.pool.ntp.org";
const long GMT_OFFSET_SEC = 8 * 3600; // 中国时区 (UTC+8)
const int DAYLIGHT_OFFSET_SEC = 0;    // 不使用夏令时

// 显示模式
enum DisplayMode
{
    DISPLAY_NORMAL,      // 常规显示
    DISPLAY_FOCUS,       // 专注模式
    DISPLAY_BREAK,       // 休息模式
    DISPLAY_HOURLY,      // 整点提醒
    DISPLAY_STUDY_STATS, // 学习统计
    DISPLAY_CLOCK_ONLY   // 仅时钟
};

// 时间提醒类型
enum ReminderType
{
    REMINDER_HOURLY,     // 整点提醒
    REMINDER_BREAK,      // 休息提醒
    REMINDER_POSTURE,    // 坐姿提醒
    REMINDER_EYE_REST,   // 护眼提醒
    REMINDER_DRINK_WATER // 喝水提醒
};

// ========== 时间管理结构体 ==========
struct TimeInfo
{
    int year;
    int month;
    int day;
    int weekday;
    int hour;
    int minute;
    int second;
    String timeString;
    String dateString;
    String weekdayString;
};

struct StudyTimeStats
{
    unsigned long totalStudyTime;   // 总学习时间 (分钟)
    unsigned long todayStudyTime;   // 今日学习时间
    unsigned long sessionStartTime; // 当前会话开始时间
    unsigned long lastBreakTime;    // 上次休息时间
    int hourlyBreakCount;           // 小时内休息次数
    int dailyStudyHours;            // 今日学习小时数
    bool isStudying;                // 是否正在学习
    bool needBreak;                 // 需要休息
};

struct DisplaySettings
{
    DisplayMode currentMode;
    int brightness;        // 显示亮度 (0-255)
    bool autoRotate;       // 自动旋转
    bool showSeconds;      // 显示秒数
    bool show24Hour;       // 24小时制
    int refreshInterval;   // 刷新间隔 (毫秒)
    bool animationEnabled; // 动画效果
};

// ========== 时间管理类 ==========
class EnhancedTimeManager
{
private:
    Adafruit_SSD1306 *display;
    TimeInfo currentTime;
    StudyTimeStats studyStats;
    DisplaySettings settings;

    unsigned long lastTimeUpdate;
    unsigned long lastDisplayUpdate;
    unsigned long lastHourlyCheck;
    unsigned long lastBreakCheck;

    bool timeInitialized;
    bool ntpSynced;

    // 音符定义 (用于蜂鸣器)
    const int NOTE_C4 = 262;
    const int NOTE_D4 = 294;
    const int NOTE_E4 = 330;
    const int NOTE_F4 = 349;
    const int NOTE_G4 = 392;
    const int NOTE_A4 = 440;
    const int NOTE_B4 = 494;
    const int NOTE_C5 = 523;

public:
    EnhancedTimeManager(Adafruit_SSD1306 *oledDisplay);

    // ========== 初始化和配置 ==========
    bool initializeTime();
    bool syncWithNTP();
    void configureDisplay(DisplayMode mode, int brightness = 128);
    void setStudyMode(bool studying);

    // ========== 时间更新和获取 ==========
    void updateTime();
    TimeInfo getCurrentTime();
    String getFormattedTime(bool includeSeconds = true);
    String getFormattedDate();
    String getWeekdayName();

    // ========== 学习时间统计 ==========
    void startStudySession();
    void endStudySession();
    void updateStudyStats();
    StudyTimeStats getStudyStats();
    String getStudyTimeReport();

    // ========== 显示功能 ==========
    void updateDisplay();
    void showNormalDisplay();
    void showFocusDisplay();
    void showBreakDisplay();
    void showHourlyReminder();
    void showStudyStats();
    void showClockOnly();

    // ========== 动画效果 ==========
    void showBootAnimation();
    void showTimeTransition();
    void showProgressBar(int percentage, String label);
    void showPulseEffect();

    // ========== 整点提醒系统 ==========
    void checkHourlyReminders();
    void performHourlyChime();
    void announceTime();
    String generateTimeAnnouncement();
    void playChimeMelody(ReminderType type);

    // ========== 智能提醒 ==========
    void checkBreakReminder();
    void checkPostureReminder();
    void checkEyeRestReminder();
    void checkWaterReminder();
    bool shouldGiveReminder(ReminderType type);

    // ========== 辅助功能 ==========
    bool isTimeToBreak();
    bool isLongStudySession();
    int calculateStudyEfficiency();
    String getMotivationalMessage();
    void resetDailyStats();

    // ========== 配置管理 ==========
    void saveTimeSettings();
    void loadTimeSettings();
    void setDisplayMode(DisplayMode mode);
    DisplayMode getDisplayMode();
};

// ========== 实现部分 ==========

EnhancedTimeManager::EnhancedTimeManager(Adafruit_SSD1306 *oledDisplay)
{
    display = oledDisplay;
    timeInitialized = false;
    ntpSynced = false;

    // 初始化设置
    settings.currentMode = DISPLAY_NORMAL;
    settings.brightness = 128;
    settings.autoRotate = false;
    settings.showSeconds = true;
    settings.show24Hour = true;
    settings.refreshInterval = 1000;
    settings.animationEnabled = true;

    // 初始化学习统计
    studyStats.totalStudyTime = 0;
    studyStats.todayStudyTime = 0;
    studyStats.sessionStartTime = 0;
    studyStats.lastBreakTime = millis();
    studyStats.hourlyBreakCount = 0;
    studyStats.dailyStudyHours = 0;
    studyStats.isStudying = false;
    studyStats.needBreak = false;

    // 初始化时间戳
    lastTimeUpdate = 0;
    lastDisplayUpdate = 0;
    lastHourlyCheck = 0;
    lastBreakCheck = 0;
}

bool EnhancedTimeManager::initializeTime()
{
    Serial.println("🕒 初始化时间管理系统...");

    // 如果WiFi已连接，尝试NTP同步
    if (WiFi.status() == WL_CONNECTED)
    {
        if (syncWithNTP())
        {
            Serial.println("✅ NTP时间同步成功");
            ntpSynced = true;
        }
        else
        {
            Serial.println("⚠️ NTP同步失败，使用本地时间");
        }
    }

    timeInitialized = true;
    updateTime();

    // 显示启动动画
    showBootAnimation();

    return timeInitialized;
}

bool EnhancedTimeManager::syncWithNTP()
{
    configTime(GMT_OFFSET_SEC, DAYLIGHT_OFFSET_SEC, NTP_SERVER1, NTP_SERVER2, NTP_SERVER3);

    // 等待时间同步
    int attempts = 0;
    while (!time(nullptr) && attempts < 10)
    {
        Serial.print(".");
        delay(1000);
        attempts++;
    }

    if (time(nullptr))
    {
        Serial.println();
        Serial.println("🌐 NTP时间同步完成");
        return true;
    }

    return false;
}

void EnhancedTimeManager::updateTime()
{
    if (millis() - lastTimeUpdate < 1000)
        return;

    time_t now = time(nullptr);
    struct tm *timeinfo = localtime(&now);

    if (timeinfo)
    {
        currentTime.year = timeinfo->tm_year + 1900;
        currentTime.month = timeinfo->tm_mon + 1;
        currentTime.day = timeinfo->tm_mday;
        currentTime.weekday = timeinfo->tm_wday;
        currentTime.hour = timeinfo->tm_hour;
        currentTime.minute = timeinfo->tm_min;
        currentTime.second = timeinfo->tm_sec;

        // 格式化时间字符串
        char timeStr[32];
        strftime(timeStr, sizeof(timeStr), "%H:%M:%S", timeinfo);
        currentTime.timeString = String(timeStr);

        char dateStr[32];
        strftime(dateStr, sizeof(dateStr), "%Y-%m-%d", timeinfo);
        currentTime.dateString = String(dateStr);

        currentTime.weekdayString = getWeekdayName();
    }

    lastTimeUpdate = millis();
}

String EnhancedTimeManager::getWeekdayName()
{
    String weekdays[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    return weekdays[currentTime.weekday];
}

void EnhancedTimeManager::startStudySession()
{
    studyStats.isStudying = true;
    studyStats.sessionStartTime = millis();
    Serial.println("📚 开始学习会话");

    setDisplayMode(DISPLAY_FOCUS);
    showProgressBar(0, "开始专注学习");
}

void EnhancedTimeManager::endStudySession()
{
    if (!studyStats.isStudying)
        return;

    unsigned long sessionDuration = (millis() - studyStats.sessionStartTime) / 60000; // 分钟
    studyStats.totalStudyTime += sessionDuration;
    studyStats.todayStudyTime += sessionDuration;
    studyStats.isStudying = false;

    Serial.println("✅ 结束学习会话，时长: " + String(sessionDuration) + " 分钟");

    setDisplayMode(DISPLAY_STUDY_STATS);
    delay(3000);
    setDisplayMode(DISPLAY_NORMAL);
}

void EnhancedTimeManager::updateDisplay()
{
    if (millis() - lastDisplayUpdate < settings.refreshInterval)
        return;

    updateTime();

    switch (settings.currentMode)
    {
    case DISPLAY_NORMAL:
        showNormalDisplay();
        break;
    case DISPLAY_FOCUS:
        showFocusDisplay();
        break;
    case DISPLAY_BREAK:
        showBreakDisplay();
        break;
    case DISPLAY_HOURLY:
        showHourlyReminder();
        break;
    case DISPLAY_STUDY_STATS:
        showStudyStats();
        break;
    case DISPLAY_CLOCK_ONLY:
        showClockOnly();
        break;
    }

    lastDisplayUpdate = millis();
}

void EnhancedTimeManager::showNormalDisplay()
{
    display->clearDisplay();

    // 标题栏
    display->setTextSize(1);
    display->setCursor(0, 0);
    display->println("=== 智能学习桌 ===");

    // 时间显示 (大字体)
    display->setTextSize(2);
    display->setCursor(0, 12);
    String timeStr = settings.showSeconds ? currentTime.timeString : currentTime.timeString.substring(0, 5);
    display->println(timeStr);

    // 日期和星期
    display->setTextSize(1);
    display->setCursor(0, 32);
    display->println(currentTime.dateString + " " + currentTime.weekdayString);

    // 学习状态
    display->setCursor(0, 42);
    if (studyStats.isStudying)
    {
        unsigned long sessionTime = (millis() - studyStats.sessionStartTime) / 60000;
        display->print("学习中: ");
        display->print(sessionTime);
        display->println(" 分钟");
    }
    else
    {
        display->println("待机状态");
    }

    // 今日统计
    display->setCursor(0, 52);
    display->print("今日: ");
    display->print(studyStats.todayStudyTime);
    display->println(" 分钟");

    display->display();
}

void EnhancedTimeManager::showFocusDisplay()
{
    display->clearDisplay();

    // 专注模式标题
    display->setTextSize(1);
    display->setCursor(20, 0);
    display->println("专注学习模式");

    // 当前时间 (小字体)
    display->setCursor(0, 12);
    display->println(currentTime.timeString);

    // 学习进度
    unsigned long sessionTime = (millis() - studyStats.sessionStartTime) / 60000;
    display->setTextSize(2);
    display->setCursor(0, 25);
    display->print(sessionTime);
    display->setTextSize(1);
    display->println(" 分钟");

    // 进度条
    int progress = min(100, (int)(sessionTime * 100 / 45)); // 45分钟为一个番茄钟
    showProgressBar(progress, "专注进度");

    // 激励信息
    display->setCursor(0, 55);
    if (sessionTime < 25)
    {
        display->println("保持专注!");
    }
    else if (sessionTime < 45)
    {
        display->println("很棒，继续坚持!");
    }
    else
    {
        display->println("可以休息了!");
    }

    display->display();
}

void EnhancedTimeManager::showBreakDisplay()
{
    display->clearDisplay();

    display->setTextSize(2);
    display->setCursor(10, 10);
    display->println("休息时间");

    display->setTextSize(1);
    display->setCursor(0, 35);
    display->println("眺望远方，放松眼睛");
    display->setCursor(0, 45);
    display->println("起身活动，伸展身体");
    display->setCursor(0, 55);
    display->println("补充水分，保持健康");

    display->display();
}

void EnhancedTimeManager::checkHourlyReminders()
{
    if (millis() - lastHourlyCheck < 30000)
        return; // 30秒检查一次

    updateTime();

    // 检查是否到达整点
    if (currentTime.minute == 0 && currentTime.second == 0)
    {
        performHourlyChime();
        setDisplayMode(DISPLAY_HOURLY);
        delay(5000);
        setDisplayMode(DISPLAY_NORMAL);
    }

    // 检查是否需要休息提醒
    checkBreakReminder();

    lastHourlyCheck = millis();
}

void EnhancedTimeManager::performHourlyChime()
{
    Serial.println("🔔 整点时间提醒");

    // 播放整点钟声
    playChimeMelody(REMINDER_HOURLY);

    // 语音播报
    String announcement = generateTimeAnnouncement();
    Serial.println("🔊 播报: " + announcement);

    // 显示整点提醒
    showHourlyReminder();
}

String EnhancedTimeManager::generateTimeAnnouncement()
{
    String announcement = "现在时间" + String(currentTime.hour) + "点整。";

    if (studyStats.isStudying)
    {
        unsigned long sessionTime = (millis() - studyStats.sessionStartTime) / 60000;
        announcement += "您已连续学习" + String(sessionTime) + "分钟。";

        if (sessionTime >= 45)
        {
            announcement += "建议休息5到10分钟。";
        }
        else
        {
            announcement += "学习状态良好，请继续保持专注。";
        }
    }
    else
    {
        announcement += "今日已学习" + String(studyStats.todayStudyTime) + "分钟。";
    }

    return announcement;
}

void EnhancedTimeManager::showHourlyReminder()
{
    display->clearDisplay();

    display->setTextSize(2);
    display->setCursor(10, 5);
    display->println("整点提醒");

    display->setTextSize(1);
    display->setCursor(0, 25);
    display->print("现在时间: ");
    display->println(currentTime.timeString);

    if (studyStats.isStudying)
    {
        unsigned long sessionTime = (millis() - studyStats.sessionStartTime) / 60000;
        display->setCursor(0, 35);
        display->print("已学习: ");
        display->print(sessionTime);
        display->println(" 分钟");

        if (sessionTime >= 45)
        {
            display->setCursor(0, 45);
            display->println("建议休息片刻");
            display->setCursor(0, 55);
            display->println("保护视力健康");
        }
    }
    else
    {
        display->setCursor(0, 35);
        display->print("今日学习: ");
        display->print(studyStats.todayStudyTime);
        display->println("分钟");
    }

    display->display();
}

void EnhancedTimeManager::playChimeMelody(ReminderType type)
{
    int buzzerPin = 42; // 根据硬件配置调整

    switch (type)
    {
    case REMINDER_HOURLY:
    {
        // 整点钟声 (类似大本钟)
        int melody[] = {NOTE_G4, NOTE_C5, NOTE_E4, NOTE_G4};
        int durations[] = {500, 500, 500, 1000};
        for (int i = 0; i < 4; i++)
        {
            tone(buzzerPin, melody[i], durations[i]);
            delay(durations[i] + 100);
            noTone(buzzerPin);
        }
        break;
    }
    case REMINDER_BREAK:
    {
        // 休息提醒 (轻松音调)
        int melody[] = {NOTE_C4, NOTE_E4, NOTE_G4, NOTE_C5};
        int durations[] = {300, 300, 300, 600};
        for (int i = 0; i < 4; i++)
        {
            tone(buzzerPin, melody[i], durations[i]);
            delay(durations[i] + 50);
            noTone(buzzerPin);
        }
        break;
    }
    case REMINDER_POSTURE:
    {
        // 坐姿提醒 (简短提示音)
        tone(buzzerPin, NOTE_A4, 200);
        delay(250);
        tone(buzzerPin, NOTE_A4, 200);
        delay(250);
        noTone(buzzerPin);
        break;
    }
    default:
        tone(buzzerPin, NOTE_C5, 300);
        delay(350);
        noTone(buzzerPin);
    }
}

void EnhancedTimeManager::checkBreakReminder()
{
    if (!studyStats.isStudying)
        return;

    unsigned long sessionTime = (millis() - studyStats.sessionStartTime) / 60000;

    // 每45分钟提醒休息
    if (sessionTime >= 45 && sessionTime % 45 == 0)
    {
        Serial.println("⏰ 休息时间到了!");
        playChimeMelody(REMINDER_BREAK);
        setDisplayMode(DISPLAY_BREAK);
        studyStats.needBreak = true;
    }

    // 每20分钟护眼提醒
    if (sessionTime > 0 && sessionTime % 20 == 0)
    {
        Serial.println("👁️ 护眼提醒");
        playChimeMelody(REMINDER_EYE_REST);
    }
}

void EnhancedTimeManager::showProgressBar(int percentage, String label)
{
    int barWidth = 100;
    int barHeight = 8;
    int barX = 14;
    int barY = 45;

    // 绘制进度条边框
    display->drawRect(barX, barY, barWidth, barHeight, SSD1306_WHITE);

    // 绘制进度条填充
    int fillWidth = (barWidth - 2) * percentage / 100;
    display->fillRect(barX + 1, barY + 1, fillWidth, barHeight - 2, SSD1306_WHITE);

    // 显示标签和百分比
    display->setTextSize(1);
    display->setCursor(barX, barY - 10);
    display->print(label);
    display->setCursor(barX + barWidth - 24, barY - 10);
    display->print(percentage);
    display->print("%");
}

void EnhancedTimeManager::showBootAnimation()
{
    // 开机动画
    display->clearDisplay();

    for (int i = 0; i <= 100; i += 10)
    {
        display->clearDisplay();

        display->setTextSize(2);
        display->setCursor(10, 10);
        display->println("智能学习桌");

        display->setTextSize(1);
        display->setCursor(20, 35);
        display->println("时间系统启动中...");

        showProgressBar(i, "初始化");

        display->display();
        delay(200);
    }

    delay(1000);
}

void EnhancedTimeManager::setDisplayMode(DisplayMode mode)
{
    settings.currentMode = mode;
}

DisplayMode EnhancedTimeManager::getDisplayMode()
{
    return settings.currentMode;
}

#endif // TIME_DISPLAY_ENHANCED_H